package com.wing.setting.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.constant.RedisConstants;
import com.wing.common.exception.BusinessException;
import com.wing.setting.dao.SystemRuleInfoDao;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.model.request.SystemRuleInfoForm;
import com.wing.setting.model.response.SystemRuleInfoVO;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 显示/规则配置-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SystemRuleInfoServiceImpl extends ServiceImpl<SystemRuleInfoDao, SystemRuleInfo> implements SystemRuleInfoService {

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public int add(SystemRuleInfoForm systemRuleInfoForm) {

        //校验

        SystemRuleInfo systemRuleInfo =new SystemRuleInfo();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SystemRuleInfo.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(systemRuleInfoForm, systemRuleInfo, copyOptions);

        return baseMapper.insert(systemRuleInfo);
    }

    @Override
    public List<SystemRuleInfoVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<SystemRuleInfoVO> pageList4app(Page page, Map<String, Object> params) {
        List<SystemRuleInfoVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public SystemRuleInfoVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public void sendMsg(SystemRuleInfo systemRuleInfo) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            syncDate(systemRuleInfo);
                        } catch (Exception e) {
                            log.error("syn SystemRuleInfoServiceImpl fail", e);
                        }
                    }
                });
            }
        });
    }

    // 数据同步
    private void syncDate(SystemRuleInfo systemRuleInfo) {
        // 同步sys_system_rule_info
        if (systemRuleInfo!=null){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                jsonObject.put("data", systemRuleInfo);
                PulsarUtils.send(topicUrl+ PulsarCommons.SYS_SYSTEM_RULE_INFO,jsonObject.toJSONString());
            }catch (Exception e){
                log.error("sync SystemRuleInfoServiceImpl err 同步失败",e);
                systemRuleInfo.setIsSyns(0);
                this.updateById(systemRuleInfo);
            }

        }
    }

    @Override
    public SystemRuleInfo getRuleInfo() {
//        String ruleInfo=null;
//        try{
//            ruleInfo=redisTemplate.opsForValue().get(RedisConstants.RULE_KEY);
//        }catch (Exception e){
//            log.error("redis get rule fail",e);
//        }
//        if (ruleInfo!=null){
//            return JSON.parseObject(ruleInfo,SystemRuleInfo.class);
//        }else{
            SystemRuleInfo systemRuleInfo=baseMapper.selectOne(new QueryWrapper<SystemRuleInfo>());
            if (systemRuleInfo==null){
                throw new BusinessException("未找到规则配置");
            }
//            try{
//                redisTemplate.opsForValue().set(RedisConstants.RULE_KEY,JSON.toJSONString(systemRuleInfo));
//            }catch (Exception e){
//                log.error("redis set rule fail",e);
//            }
            return systemRuleInfo;
//        }
    }


}
